package com.lanou.projecta.tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.android.volley.toolbox.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by dllo on 16/1/18.
 */
public class DiskCache1 implements ImageLoader.ImageCache {
    String cacheDir = "";

    public DiskCache1() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)){
            File root=Environment
                    .getExternalStorageDirectory();
            File file = new File(root+"/cache");
            if (!file.exists()){
                file.mkdir();
            }
            cacheDir = file.getAbsolutePath();
        }
    }

    @Override
    public Bitmap getBitmap(String url) {
        url = url.substring(url.lastIndexOf("/"),url.lastIndexOf(".")+4);

        return BitmapFactory.decodeFile(cacheDir+"/"+url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        FileOutputStream fileOutputStream = null;
        try {
            url = url.substring(url.lastIndexOf("/"),url.lastIndexOf(".")+4);
            fileOutputStream = new FileOutputStream(cacheDir +"/"+ url);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
